import React, { useEffect, useState, useImperativeHandle, forwardRef } from 'react';
import { Button, Table, Input } from 'antd';
import { cloneDeep } from 'lodash';

const CodeMap = forwardRef((props, ref) => {
  const { record, value } = props;
  const [data, setData] = useState([]);

  useEffect(() => {
    if (record.codeMap) {
      const { innerPath } = record;
      record.codeMap.forEach((item) => (item.destKey = innerPath));
      setData(cloneDeep(record.codeMap));
    } else {
      handleReset();
    }
  }, []);

  useImperativeHandle(ref, () => ({
    getData: () => {
      data.forEach((item) => {
        if (item.destCode === '') {
          throw '映射码值不能为空';
        }
      });
      return data;
    },
  }));

  // 添加
  const hanldAdd = () => {
    const tempData = [...data];
    const { innerPath } = record;
    const tempObj = {
      destKey: innerPath,
      destCode: '',
      destDesc: '',
    };
    value.thirdList.forEach((item) => {
      tempObj[`srcCode-${item.id}`] = '';
    });
    tempData.push(tempObj);
    setData(tempData);
  };

  const handleChange = (value, index, key) => {
    const tempData = [...data];
    if (key.includes('srcCode')) {
      const new_value = value.match(/[a-zA-Z0-9\u4e00-\u9fa5,]+/);
      tempData[index][key] = new_value ? new_value[0] : '';
    } else {
      tempData[index][key] = value;
    }
    setData(tempData);
  };

  // 码值映射重置
  const handleReset = () => {
    setData([]);
  };

  const handleDelete = (index) => {
    const tempData = [...data];
    tempData.splice(index, 1);
    setData(tempData);
  };

  const columns = [
    {
      title: '映射key',
      dataIndex: 'destKey',
    },
    {
      title: '码值',
      children: value.thirdList.map((item) => ({
        title: item.name,
        dataIndex: `srcCode-${item.id}`,
        render: (text, _, index) => (
          <Input value={text} onChange={(e) => handleChange(e.target.value, index, `srcCode-${item.id}`)} />
        ),
      })),
    },

    {
      title: '映射码值',
      dataIndex: 'destCode',
      render: (text, _, index) => (
        <Input value={text} onChange={(e) => handleChange(e.target.value, index, 'destCode')} />
      ),
    },
    {
      title: '描述',
      dataIndex: 'destDesc',
      render: (text, _, index) => (
        <Input value={text} onChange={(e) => handleChange(e.target.value, index, 'destDesc')} />
      ),
    },
    {
      title: '删除',
      dataIndex: 'action',
      render: (_, __, index) => (
        <Button type='text' onClick={() => handleDelete(index)}>
          删除
        </Button>
      ),
    },
  ];

  return (
    <div>
      <Button onClick={hanldAdd}>增加</Button>
      <Table
        bordered
        dataSource={data}
        columns={columns}
        rowKey={(_, index) => index}
        pagination={false}
        style={{ marginBottom: '20px' }}
      />
    </div>
  );
});
export default CodeMap;
